package cf.huzpsb.bcgod;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public final class Main extends Plugin {
    public static Configuration bancfg;
    public static Configuration horncfg;
    public static Configuration passcfg;
    public static Configuration namecfg;
    public static Configuration codecfg;
    public static Configuration config;
    public static Configuration groupcfg;
    public static String hub;
    public static String login;
    public static String banreason;
    public static String kickr;
    public static String ssr;
    public static boolean uselogin;
    public static boolean nof;
    public static boolean and;
    public static Set<String> nobot = new HashSet<>();
    public static boolean nbt;
    public static String Announce;
    public static int delay;
    public static String opls;
    public static int spamth;
    public static int cool;
    public static int save;
    public static String codes;
    public static boolean bypass;
    public static Map<ProxiedPlayer, Long> cooler = new HashMap<>();
    public static Set<Character> hs = new HashSet();
    public static Pattern pt = Pattern.compile("^[0-9a-zA-Z_]+$");
    private static boolean preview;
    private static boolean autosave;
    private static String previewcode;
    private static ConfigurationProvider banpvd;
    private static ConfigurationProvider hornpvd;
    private static ConfigurationProvider passpvd;
    private static ConfigurationProvider namepvd;
    private static ConfigurationProvider codepvd;
    private static ConfigurationProvider grouppvd;
    private static File banfile;
    private static File hornfile;
    private static File passfile;
    private static File namefile;
    private static File codefile;
    private static File groupfile;
    private Map<ProxiedPlayer, Data> allData = new HashMap();
    private int tban;

    public static Main getInstance() {
        return (Main) ProxyServer.getInstance().getPluginManager().getPlugin("bcgod");
    }

    public static void save() {
        try {
            banpvd.save(bancfg, banfile);
            hornpvd.save(horncfg, hornfile);
            passpvd.save(passcfg, passfile);
            namepvd.save(namecfg, namefile);
            codepvd.save(codecfg, codefile);
            grouppvd.save(groupcfg, groupfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onEnable() {
        this.getLogger().info("§c欢迎使用BCGod公开预览版! 作者:huzpsb 构建号:git-happynewyear-sp1");
        this.getLogger().info("§c插件正在初始化,请稍候...");
        this.initCFG();
        this.installCMD();
        this.initDic();
        this.getProxy().getPluginManager().registerListener(this, new PlayerListener());
        if (tban != -1) {
            this.getLogger().info("§cTban模拟器正在启动...");
            TbanAdapt tb = new TbanAdapt(tban);
            Thread t = new Thread(tb);
            t.start();
        }
        this.getLogger().info("§c插件已经启动!感谢您使用本插件!");
    }

    private String ReadWeb(String p) {
        try {
            HttpURLConnection Web = (HttpURLConnection) new URL(p).openConnection();
            Web.setConnectTimeout(3000);
            Web.setRequestMethod("GET");
            InputStream inStream = Web.getInputStream();
            StringBuilder builder = new StringBuilder();
            while (true) {
                int byteRead = inStream.read();
                if (byteRead == -1) {
                    return builder.toString();
                }
                builder.append((char) byteRead);
            }
        } catch (Exception e) {
            return "ERROR";
        }
    }

    @Override
    public void onDisable() {
        this.getLogger().info("§c感谢您使用BCGod预览版! 作者:huzpsb");
        this.getLogger().info("§c开始保存封禁列表,用户密码,充值卡和欢乐券个数...");
        save();
        this.getLogger().info("§c保存成功!插件即将关闭!期待我们还能再会!");
    }

    private void initDic() {
        hs.add('1');
        hs.add('2');
        hs.add('3');
        hs.add('4');
        hs.add('5');
        hs.add('6');
        hs.add('7');
        hs.add('8');
        hs.add('9');
        hs.add('0');
        hs.add('#');
        hs.add('^');
        hs.add('%');
        hs.add('$');
        hs.add('@');
        hs.add(':');
        hs.add('q');
        hs.add('w');
        hs.add('e');
        hs.add('r');
        hs.add('t');
        hs.add('y');
        hs.add('u');
        hs.add('i');
        hs.add('o');
        hs.add('p');
        hs.add('a');
        hs.add('s');
        hs.add('d');
        hs.add('f');
        hs.add('g');
        hs.add('h');
        hs.add('j');
        hs.add('k');
        hs.add('l');
        hs.add('z');
        hs.add('x');
        hs.add('c');
        hs.add('v');
        hs.add('b');
        hs.add('n');
        hs.add('m');
        hs.add('Q');
        hs.add('W');
        hs.add('E');
        hs.add('R');
        hs.add('T');
        hs.add('Y');
        hs.add('U');
        hs.add('I');
        hs.add('O');
        hs.add('P');
        hs.add('A');
        hs.add('S');
        hs.add('D');
        hs.add('F');
        hs.add('G');
        hs.add('H');
        hs.add('J');
        hs.add('K');
        hs.add('L');
        hs.add('Z');
        hs.add('X');
        hs.add('C');
        hs.add('V');
        hs.add('B');
        hs.add('N');
        hs.add('M');
        hs.add(' ');
        hs.add('_');
    }

    private void initCFG() {
        //init files
        try {
            if (!this.getDataFolder().exists()) {
                this.getDataFolder().mkdir();
            }

            File config = new File(this.getDataFolder(), "config.yml");
            if (!config.exists()) {
                Files.copy(this.getResourceAsStream("config.yml"), config.toPath());
            }
            Main.config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(new File(this.getDataFolder(), "config.yml"));

            File ban = new File(this.getDataFolder(), "ban.yml");
            if (!ban.exists()) {
                Files.copy(this.getResourceAsStream("ban.yml"), ban.toPath());
            }
            banpvd = ConfigurationProvider.getProvider(YamlConfiguration.class);
            banfile = new File(this.getDataFolder(), "ban.yml");
            bancfg = banpvd.load(banfile);

            File horn = new File(this.getDataFolder(), "horn.yml");
            if (!horn.exists()) {
                Files.copy(this.getResourceAsStream("horn.yml"), horn.toPath());
            }
            hornpvd = ConfigurationProvider.getProvider(YamlConfiguration.class);
            hornfile = new File(this.getDataFolder(), "horn.yml");
            horncfg = hornpvd.load(hornfile);

            File pass = new File(this.getDataFolder(), "pass.yml");
            if (!pass.exists()) {
                Files.copy(this.getResourceAsStream("pass.yml"), pass.toPath());
            }
            passpvd = ConfigurationProvider.getProvider(YamlConfiguration.class);
            passfile = new File(this.getDataFolder(), "pass.yml");
            passcfg = passpvd.load(passfile);

            File name = new File(this.getDataFolder(), "names.yml");
            if (!name.exists()) {
                Files.copy(this.getResourceAsStream("names.yml"), name.toPath());
            }
            namepvd = ConfigurationProvider.getProvider(YamlConfiguration.class);
            namefile = new File(this.getDataFolder(), "names.yml");
            namecfg = namepvd.load(namefile);

            File code = new File(this.getDataFolder(), "codes.yml");
            if (!code.exists()) {
                Files.copy(this.getResourceAsStream("codes.yml"), code.toPath());
            }
            codepvd = ConfigurationProvider.getProvider(YamlConfiguration.class);
            codefile = new File(this.getDataFolder(), "codes.yml");
            codecfg = codepvd.load(codefile);

            File group = new File(this.getDataFolder(), "group.yml");
            if (!group.exists()) {
                Files.copy(this.getResourceAsStream("group.yml"), group.toPath());
            }
            grouppvd = ConfigurationProvider.getProvider(YamlConfiguration.class);
            groupfile = new File(this.getDataFolder(), "group.yml");
            groupcfg = grouppvd.load(groupfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //pcodes
        previewcode = config.getString("bcgod.previewcode");
        preview = false;
        if (!previewcode.equalsIgnoreCase("none")) {
            String code = ReadWeb("https://huzpsb.github.io/reg/" + previewcode + "/");
            if (code.startsWith("bcgod")) {
                preview = true;
                this.getLogger().info("§c您正在运行调试模式!本插件将产生许多特性!");
                this.getLogger().info("§c您请一定要确定自己想好了!后果自负!真的!");
            } else {
                this.getLogger().info("§c预览码错误或网络错误.您正在运行稳定模式...");
            }
        } else {
            if (previewcode.equals("None")) {
                preview = true;
                this.getLogger().info("§c您正在运行开发模式!如果您不是开发者请立即关闭服务器,并删除BcGod的所有配置!");
            } else {
                this.getLogger().info("§c您正在运行稳定模式...");
            }
        }
        //cfgs
        hub = config.getString("bcgod.hub");
        login = config.getString("bcgod.login");
        banreason = config.getString("bcgod.banmsg").replaceAll("&n", "\n").replaceAll("&", "§");
        kickr = config.getString("bcgod.kickmsg").replaceAll("&n", "\n").replaceAll("&", "§");
        ssr = config.getString("bcgod.ssmsg").replaceAll("&n", "\n").replaceAll("&", "§");
        nof = config.getBoolean("bcgod.antiforge");
        and = config.getBoolean("bcgod.antidup");
        nbt = config.getBoolean("bcgod.nobot");
        tban = config.getInt("bcgod.tban");
        delay = config.getInt("bcgod.delay");
        Announce = config.getString("bcgod.announce").replaceAll("&n", "\n").replaceAll("&", "§");
        opls = config.getString("bcgod.opl").replaceAll("&n", "\n").replaceAll("&", "§");
        spamth = config.getInt("bcgod.spamc");
        cool = config.getInt("bcgod.ccool");
        uselogin = config.getBoolean("bcgod.uselogin");
        autosave = config.getBoolean("bcgod.autosave");
        save = config.getInt("bcgod.savetime");
        bypass = config.getBoolean("bcgod.bypassnc");
        codes = config.getString("bcgod.codes");
        //Threads
        if (delay > 0) {
            TimeTasker tsk = new TimeTasker();
            Thread thr = new Thread(tsk);
            thr.start();
        }
        if (autosave) {
            this.getLogger().info("§c自动保存系统正在启动...");
            AutoSaver stsk = new AutoSaver();
            Thread sthr = new Thread(stsk);
            sthr.start();
            this.getLogger().info("§c自动保存系统启动成功!");

        }
        if (bypass) {
            if (preview) {
                this.getLogger().info("§c警告:您关闭了用户名约规检测.这可能带来很多安全隐患,请保重!");
            } else {
                this.getLogger().info("§c用户名约规检测关闭失败:此为危险操作且您没有使用内测码.");
                bypass = false;
            }
        }
    }

    private void installCMD() {
        this.getProxy().getPluginManager().registerCommand(this, new ShoutCMD("shout", "bcgod.shout", "zh"));
        this.getProxy().getPluginManager().registerCommand(this, new TpCMD("call", "bcgod.tp", "allowtp"));
        this.getProxy().getPluginManager().registerCommand(this, new TidCMD("tid", "bcgod.tid", "lb"));
        this.getProxy().getPluginManager().registerCommand(this, new BanCMD("ban", "bcgod.ban", "remove"));
        this.getProxy().getPluginManager().registerCommand(this, new UnbanCMD("unban", "bcgod.unban", "pardon"));
        this.getProxy().getPluginManager().registerCommand(this, new KickCMD("kick", "bcgod.kick", "t"));
        this.getProxy().getPluginManager().registerCommand(this, new HubCMD("hub", "bcgod.hub", "lobby"));
        this.getProxy().getPluginManager().registerCommand(this, new SsCMD("ss", "bcgod.ss", "offlineban"));
        this.getProxy().getPluginManager().registerCommand(this, new AskopCMD("askop", "bcgod.askop", "qz"));
        this.getProxy().getPluginManager().registerCommand(this, new PmCMD("pm", "bcgod.pm", "bcchat"));
        this.getProxy().getPluginManager().registerCommand(this, new InfoCMD("info", "bcgod.info", "ip"));
        this.getProxy().getPluginManager().registerCommand(this, new SudoCMD("bsudo", "bcgod.sudo", "trick"));
        this.getProxy().getPluginManager().registerCommand(this, new ListCMD("blist", "bcgod.list", "listall"));
        this.getProxy().getPluginManager().registerCommand(this, new HornCMD("horn", "bcgod.horn", "slb"));
        this.getProxy().getPluginManager().registerCommand(this, new PointsCMD("bpoint", "bcgod.point", "kejin"));
        this.getProxy().getPluginManager().registerCommand(this, new CodeCMD("bcode", "bcgod.code", "cz"));
        this.getProxy().getPluginManager().registerCommand(this, new VipCMD("vip", "bcgod.vip", "duihuan"));
        this.getProxy().getPluginManager().registerCommand(this, new GroupCMD("group", "bcgod.group", "perm"));
        if (uselogin) {
            this.getLogger().info("§cBcGod登录系统正在启动...");
            this.getProxy().getPluginManager().registerCommand(this, new LoginCMD("dl", "bcgod.login", "login"));
            this.getProxy().getPluginManager().registerCommand(this, new SetpassCMD("setpass", "bcgod.setpass", "gm"));
            this.getProxy().getPluginManager().registerCommand(this, new RegCMD("zc", "bcgod.register", "register"));
            this.getLogger().info("§cBcGod登录系统启动成功!");
        }
    }

    public Map<ProxiedPlayer, Data> getAllData() {
        return this.allData;
    }
}
